<script lang="ts">
import { ref, onMounted } from "vue";
console.log("performance:", window.performance.timing);
import TopProgress from '../components/TopProgress.vue';
export default {
  components:{
    TopProgress
  },
  setup() {
    const imagesList = ref<string[]>([]);
    const imageUrl = ref(
      "/src/assets/images/78c2db6f5076789d3f1e474983bbfce4.jpeg"
    );
    const title = ref(null);
    const imageRefs = ref<HTMLImageElement[]>([]); // 存储图片元素的引用
    let count = 0;
    // 使用 import.meta.glob 动态加载图片
    const modules = import.meta.glob("/src/assets/images/*.{jpeg,jpg,png}");

    onMounted(async () => {
      const timing = performance.timing;
      console.log(title.value);
      if (title.value) console.log(title.value);
      console.log(imageRefs.value);
      console.log(modules);
      // 遍历模块，加载图片
      for (const path in modules) {
        console.log(path);
        const module = (await modules[path]()) as { default: string }; // 加载模块
        imagesList.value.push(module.default); // 将图片路径添加到数组中
      }
      if (imageRefs.value) console.log(imageRefs.value);
      console.log(imagesList.value.length);
      console.log(imageRefs.value);
      // 创建 IntersectionObserver 实例
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              const img = entry.target as HTMLImageElement; // 类型断言
              img.src = img.dataset.src!; // 加载图片
              observer.unobserve(img); // 停止监听
            }
          });
        },
        {
          rootMargin: "0px", // 视口边界扩展
          threshold: 0.15, // 交叉比例阈值
        }
      );
      // 设置延迟执行，可以避免最后一张图不显示的问题
      setTimeout(() => {
        // 监听所有图片元素
        imageRefs.value.forEach((el) => {
          observer.observe(el); // 开始监听
        });
      }, 20);

    });

    return {
      imagesList,
      title,
      imageRefs,
      imageUrl,
    };
  },
};
</script>
<template>
  <div>
  <TopProgress></TopProgress>
    <h3>imgages</h3>
    <h5 ref="title">v-lazy</h5>
    <!-- <img  v-lazy="imageUrl"/> -->
    <h3>v-lazy自定义指令实现懒加载</h3>
    <div>
      <img
        v-for="(src, index) in imagesList"
        :key="index"
        v-lazy="src"
        style="width: 600px; height: 200px; object-fit: cover"
        alt="Lazy Loaded Image"
      />
    </div>
    <h3>自定义手写懒加载</h3>
    <hr />
    <div class="lazy-load">
      <img
        v-for="(src, index) in imagesList"
        :key="index"
        :data-src="src"
        alt="Lazy Loaded Image"
        class="lazy-image"
        ref="imageRefs"
      />
    </div>
    <div style="height: 5vh"></div>
  </div>
</template>

<style>
.lazy-load {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.lazy-image {
  width: 600px;
  height: 400px;
  background-color: #f0f0f0;
}
</style>
